package com.stylefeng.guns.rest.modular.wz.util;

import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.modular.wz.api.v3.Dto.TencentPushDto;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @program: wz_dev_app_shop
 * @description:
 * @author: Chenchao
 * @create: 2018-11-22 16:21
 **/
@Component
public class TencentPushUtil {
    protected final static Logger logger = LoggerFactory.getLogger(TencentPushUtil.class);

    private static String sig = Consts.adminSig;
    private static String sdkappid = Consts.sdkappid;

    //推送Url
    private static String pushUrl = "https://console.tim.qq.com/v4/openim/im_push?usersig=" + sig + "&apn=1&identifier=admin&sdkappid="+sdkappid+"&contenttype=json";
    //获取用户属性
    private static String getAttrUrl = "https://console.tim.qq.com/v4/openim/im_get_attr?usersig=" + sig + "&apn=1&identifier=admin&sdkappid="+sdkappid+"&contenttype=json";
    //设置用户属性
    private static String setAttrUrl = "https://console.tim.qq.com/v4/openim/im_set_attr?usersig=" + sig + "&apn=1&identifier=admin&sdkappid="+sdkappid+"&contenttype=json";

    public static void pushToAll(String title, String subtitle) {
        TencentPushDto pushDto=new TencentPushDto();
        JSONObject json = pushDto.init(title,subtitle,null);
        JSONObject result=doPost(pushUrl,json);
        if("OK".equals(result.get("ActionStatus"))){
            logger.info("推送全体成功");
        }else{
            logger.info("推送全体失败"+result.get("ErrorInfo"));
            pushToAll(title,subtitle);
        }
    }

    public static void pushToOneByUserCode(String title, String subtitle,String userCode) {
        TencentPushDto pushDto=new TencentPushDto();
        JSONObject getjson =pushDto.initGetAttr(userCode);
        //获取用户属性
        JSONObject attrresult=doPost(getAttrUrl,getjson);
        if("OK".equals(attrresult.get("ActionStatus"))){
            //已经设置属性 ...
        }else{
            //未设置属性
            JSONObject setjson = pushDto.initSetAttr(userCode);
            JSONObject setResult=doPost(setAttrUrl,setjson);
        }
        JSONObject json = pushDto.init(title,subtitle,userCode);
        JSONObject result=doPost(pushUrl,json);
        if("OK".equals(result.get("ActionStatus"))){
            logger.info("推送单个用户成功");
        }else{
            logger.info("推送单个用户失败"+result.get("ErrorInfo"));
            pushToOneByUserCode(title,subtitle,userCode);
        }


    }

    //json格式发送post请求
    public static JSONObject doPost(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(),"utf-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
}
